package com.day16;

import com.day15.User;
import org.junit.Test;

import java.util.*;

public class TreeMapTest {

    //向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
    //因为要按照key进行排序，自然排序

    //自然排序
    @Test
    public void test1(){

        TreeMap treeMap = new TreeMap();

        User user = new User("Tom",23);
        User user1 = new User("Tom",23);
        User user2 = new User("Tom",23);
        User user3 = new User("Tom",23);
        User user4 = new User("Tom",23);

        treeMap.put(user, 98);
        treeMap.put(user1, 89);
        treeMap.put(user2, 100);
        treeMap.put(user3, 23);
        treeMap.put(user4, 60);


        Set set = treeMap.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        }
    }

    //定制排序
    @Test
    public void test2(){
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });

        User user = new User("Tom",23);
        User user1 = new User("Tom",23);
        User user2 = new User("Tom",23);
        User user3 = new User("Tom",23);
        User user4 = new User("Tom",23);

        treeMap.put(user, 98);
        treeMap.put(user1, 89);
        treeMap.put(user2, 100);
        treeMap.put(user3, 23);
        treeMap.put(user4, 60);


    }
}
